<template>
  <el-container class="top">
    <el-header>
      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-form-item label="设备编号：">
          <el-input v-model="value" placeholder="请输入" size="medium" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit"><i class="el-icon-search" style="margin-right:5px" />查询</el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <el-main>
      <el-row>
        <el-button type="warning" @click="openAdd">
          <i class="el-icon-circle-plus-outline" style="margin-right:5px" />新建
        </el-button>
        <el-button class="btn" @click="openLargeStraDialog">批量操作</el-button>
      </el-row>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :header-cell-style="{ backgroundColor: '#f3f6fb', fontweight: 400 }"
        @select="largeStraMsg"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          label="序号"
        >
          <template slot-scope="scope">
            <span>{{ scope.$index+(queryObj.pageIndex - 1) * queryObj.pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="innerCode"
          label="设备编号"
        />
        <el-table-column
          prop="type.name"
          label="设备型号"
          show-overflow-tooltip
        />
        <el-table-column
          prop="node.name"
          label="详细地址"
        />
        <el-table-column
          prop="node.ownerName"
          label="合作商"
        />
        <el-table-column
          prop="address"
          label="设备状态"
          show-overflow-tooltip
        >
          <template #default="{row}">
            <span>{{ row.vmStatus===0?'未投放':row.vmStatus===1?'运营':'撤机' }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          show-overflow-tooltip
        >
          <template #default="{row}">
            <el-button type="text" @click="openCargo(row)">货道</el-button>
            <el-button type="text" @click="openTactics(row.innerCode)">策略</el-button>
            <el-button type="text" @click="edit(row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 策略 -->
      <el-dialog
        v-if="datas"
        title="策略管理"
        :visible.sync="dialogVisible"
        width="30%"
      >
        <div class="dialogBox">
          <span>机器编号：{{ datas.innerCode }}</span>
          <span>策略名称：{{ datas.policyName }}</span>
          <span>策略方案：{{ datas.discount }}%</span>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button style="margin-right:40%; background-color:#fbf4f0" @click="delPolicy(datas)">取消策略</el-button>
        </span>
      </el-dialog>

      <el-dialog
        v-else
        title="策略管理"
        :visible.sync="dialogVisible"
        width="30%"
      >
        <div>
          选择策略： <el-select v-model="selectedStra" placeholder="请选择" style="width:80%">
            <el-option
              v-for="item in policyOption"
              :key="item.policyId"
              :label="item.policyName"
              :value="item.policyId"
            />
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button style="background-color:#fbf4f0" @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" style="margin-right:35%;background-color:#ff8c3c" @click="update">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 新增 -->
      <el-dialog
        title="新增设备"
        :visible.sync="showDialog"
        width="30%"
        class="addList"
        :center="true"
      >
        <div>
          <span>设备编号：系统自动生成</span>
          <el-form ref="form" label-width="150px" :model="form" :rules="rules">
            <el-form-item label="选择型号：">
              <el-select v-model="form.vmType" placeholder="请选择" style="width:300px">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.typeId"
                  :label="item.name"
                  :value="item.typeId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="选择点位：">
              <el-select v-model="form.nodeId" placeholder="请选择" style="width:300px">
                <el-option
                  v-for="(item,index) in pointsOptions"
                  :key="index"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="addSubmit">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改 -->
      <el-dialog
        title="修改设备"
        :visible.sync="updateDialog"
        width="30%"
        @close="updateDialog=false"
      >
        <el-form label-width="140px">
          <el-form-item label="机器编号：">
            <div>{{ info.innerCode }}</div>
          </el-form-item>
          <el-form-item label="供货时间：">
            <div>{{ info.lastSupplyTime }}</div>
          </el-form-item>
          <el-form-item label="设备类型：">
            <div>{{ info.type.name }}</div>
          </el-form-item>
          <el-form-item label="设备容量：">
            <div>{{ info.type.channelMaxCapacity }}</div>
          </el-form-item>
          <el-form-item label="设备点位：">
            <el-select :value="info.node.id" placeholder="请选择" @change="changeNode">
              <el-option
                v-for="item in pointsOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="合作商：">
            <div>{{ info.ownerName }}</div>
          </el-form-item>
          <el-form-item label="所属区域：">
            <div>{{ info.region.name }}</div>
          </el-form-item>
          <el-form-item label="设备地址：">
            <div>{{ info.node.addr }}</div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="updateDialog=false">取 消</el-button>
          <el-button type="primary" @click="editPoint(info.id,info.nodeId)">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 批量策略管理 -->
      <el-dialog
        title="批量策略管理"
        :visible.sync="largeStraDialog"
        width="40%"
      >
        <el-form label-width="140px">
          <el-form-item label="选择策略：">
            <el-select v-model="selectedStra">
              <el-option
                v-for="item in policyOption"
                :key="item.policyId"
                :label="item.policyName"
                :value="item.policyId"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="largeStraDialog = false">取 消</el-button>
          <el-button type="primary" @click="edieAllPolicy">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分页 -->
      <PageTool
        class="foot"
        :info="queryObj"
        @handleCurrentChange="handleCurrentChange"
      />
    </el-main>
    <!-- 货道 -->
    <CargoWay
      :id="id"
      :dialog-cargo.sync="dialogCargo"
      :list="cargoList"
      :title="cargoTitle"
    />
  </el-container>
</template>

<script>
import {
  getList,
  vmTypeList,
  add,
  vmPolicy,
  getpolicy,
  removePolicy,
  updatePolicy,
  updatepoint,
  getCargoList
} from '@/api/equipment.js'
import { getPoints } from '@/api/point/pointS'
import { getStrategy } from '@/api/strategy'
import PageTool from '../components/page-tool.vue'
import CargoWay from '../components/cargoWay.vue'
export default {
  name: 'Management',
  components: {
    PageTool,
    CargoWay
  },
  data() {
    return {
      value: '',
      dialogVisible: false,
      showDialog: false,
      updateDialog: false,
      dialogCargo: false,
      largeStraDialog: false,
      isSelected: null,
      form: {
        vmType: null,
        nodeId: null,
        createUserId: 1
      },
      rules: {},
      tableData: [],
      queryObj: {
        pageIndex: 1,
        pageSize: 10,
        totalCount: 10,
        totalPage: 10,
        innerCode: null
      },
      datas: {},
      policyName: '',
      typeOptions: [],
      pointsOptions: [],
      info: {
        innerCode: '',
        lastSupplyTime: '',
        type: {
          name: '',
          channelMaxCapacity: ''
        },
        ownerName: '',
        region: {
          name: ''
        },
        node: {
          addr: '',
          name: ''
        }
      },
      editQuery: {
        id: '',
        nodeId: ''
      },
      policyOption: [],
      name: '',
      cargoTitle: {},
      cargoList: {},
      id: 0,
      selectedStra: null,
      updateObj: {
        innerCodeList: [],
        policyId: ''
      }
    }
  },
  created() {
    this.getManagementList()
  },
  methods: {
    async getManagementList() {
      const data = await getList(this.queryObj)
      this.tableData = data.currentPageRecords
      this.queryObj.pageIndex = data.pageIndex
      this.queryObj.pageSize = data.pageSize
      this.queryObj.totalCount = data.totalCount
      this.queryObj.totalPage = data.totalPage
      this.tableData.forEach(item => {
        return this.updateObj.innerCodeList.push(item.innerCode)
      })
    },
    handleCurrentChange(val) {
      this.queryObj.pageIndex = val
      this.getManagementList()
    },
    onSubmit() {
      this.queryObj.innerCode = this.value
      this.getManagementList()
    },
    async openTactics(id) {
      if (id) {
        const data = await vmPolicy(id)
        console.log(data)
        this.datas = data
      }
      const res = await getpolicy()
      console.log(res)
      this.policyOption = res
      this.dialogVisible = true
    },
    async openAdd() {
      const data = await vmTypeList(this.queryObj)
      this.typeOptions = data.currentPageRecords
      const info = await getPoints(this.queryObj)
      const res = []
      info.currentPageRecords.forEach(item => {
        res.push(item.name)
      })
      this.pointsOptions = [...res]
      this.showDialog = true
    },
    async addSubmit() {
      const data = await add({ vmType: this.form.vmType, nodeId: this.form.nodeId, createUserId: this.form.createUserId })
      console.log(data)
    },
    async edit(row) {
      this.info = { ...row }
      this.editQuery.id = row.id
      this.name = row.node.name
      const { currentPageRecords } = await getPoints(this.queryObj)
      const arr = currentPageRecords.map(item => {
        return { name: item.name, id: item.id }
      })
      this.pointsOptions = arr
      this.updateDialog = true
    },
    // 修改策略
    async update() {
      const res = await getStrategy()
      const info = res.currentPageRecords.find(item => item.policyId === this.selectedStra)
      console.log(info)
      this.updateObj.policyId = info.policyId
      await updatePolicy(this.updateObj)
      this.$message.success('修改成功')
      this.getManagementList()
      this.dialogVisible = false
    },
    changeNode(value) {
      this.info.node.id = value
      this.editQuery.nodeId = value
    },
    async editPoint() {
      try {
        console.log(this.editQuery.nodeId)
        await updatepoint(this.editQuery.id, this.editQuery.nodeId)
        this.$message.success('修改成功')
        this.getManagementList()
      } catch (error) {
        this.$message.error('该设备正在使用中')
      }
      this.updateDialog = false
    },
    // 取消策略
    async delPolicy(data) {
      await removePolicy(data.innerCode, data.policyId)
      this.$message.success('取消策略成功')
      this.dialogVisible = false
      this.getManagementList()
    },
    async openCargo(row) {
      this.id = Number(row.businessId)
      this.cargoTitle = row.type
      const data = await getCargoList(row.innerCode)
      const res = data.filter(item => item.sku)
      this.cargoList = { ...res }
      console.log(this.cargoList)
      this.dialogCargo = true
    },
    largeStraMsg(selection) {
      this.isSelected = selection
    },
    // 批量修改策略
    async openLargeStraDialog() {
      if (!this.isSelected) {
        this.$message.warning('请勾选售货机')
      } else {
        const res = await getpolicy()
        this.policyOption = res
        this.largeStraDialog = true
      }
    },
    async edieAllPolicy() {
      const info = this.policyOption.find(item => item.policyId === this.selectedStra)
      this.updateObj.policyId = info.policyId
      await updatePolicy(this.updateObj)
      this.$message.success('修改成功')
      this.getManagementList()
      this.largeStraDialog = false
    }
  }
}

</script>

<style scoped lang='scss'>
.top{
  margin-top: 70px;
}
.el-row {
  margin-bottom: 10px;
}
.btn {
  background-color: #fbf4f0;
}
.dialogBox{
  display: flex;
  flex-wrap: wrap;
  span {
   margin: 10px 50px;
  }
}
.foot {
 margin-bottom: 0px;
}
.addList{
  span {
    margin:10px 70px;
  };
  .el-form {
    margin-top: 20px;
  }
}
</style>
